package foo.bar.wiki.web.action.general;

import foo.bar.wiki.web.action.BaseActionBean;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import org.springframework.orm.jpa.JpaTemplate;
import org.springframework.orm.jpa.JpaCallback;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import java.util.List;

/**
 * @author tmjee
 * @version $Date$ $Id$
 */
public class QueryActionBean extends BaseActionBean{

    public static final String VIEW = "/general/query.jsp";

    private String query;

    private JpaTemplate template;

    private List resultList;


    @DefaultHandler
    public Resolution view() {
        return new ForwardResolution(generateThemePath(VIEW));    
    }

    public Resolution query() {
        resultList = (List) template.execute(new JpaCallback(){
            public Object doInJpa(EntityManager em) throws PersistenceException {
                Query q = em.createQuery(query);
                return q.getResultList();
            }
        });
        return new ForwardResolution(generateThemePath(VIEW));
    }


    @SpringBean("jpaTemplate")
    public void setJpaTemplate(JpaTemplate template) {
        this.template = template;
    }

    public String getQuery() {
        return query;
    }

    public void setQuery(String query) {
        this.query = query;
    }

    public List getResultList() {
        return resultList;
    }

    public void setResultList(List resultList) {
        this.resultList = resultList;
    }
}


